package com.panshi.controller;

import com.google.code.kaptcha.Producer;
import com.panshi.entity.AppUserMassageT;
import com.panshi.entity.AppUserT;
import com.panshi.result.R;
import com.panshi.service.UserClientService;
import com.panshi.util.BaseUpload;
import com.panshi.util.UserInfoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.mail.MessagingException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    private Producer producer;

    @Autowired
    private UserInfoUtils userInfoUtils;


    @Autowired
    private UserClientService userClientService;

    @Autowired
    private BaseUpload baseUpload;

    @GetMapping("/msgindex/{userId}")
    public String userMsgIndex(@PathVariable int userId, HttpServletResponse response , HttpServletRequest request, Model model){
        System.out.println("用户个人信息"+userId);
        System.out.println(userId);
        AppUserT uservo = userInfoUtils.getuser(request, response);
        if(uservo==null){
            return "login/login";
        }
        if(uservo.getUserId()==null){
            return "login/login";
        }
        model.addAttribute("uservo",uservo);

        return "user/user_msgindex";
    }


    @GetMapping("/userStation/{userId}")
    public String userStation(@PathVariable int userId, HttpServletResponse response , HttpServletRequest request, Model model){

        System.out.println("用户个人信息"+userId);
        System.out.println(userId);
        AppUserT uservo = userInfoUtils.getuser(request, response);
        if(uservo==null){
            return "login/login";
        }
        if(uservo.getUserId()==null){
            return "login/login";
        }
        model.addAttribute("uservo",uservo);

        List<AppUserMassageT> userMassage = userClientService.getUserMassage(uservo.getUserId(),1);
        model.addAttribute("userMassage",userMassage);
        return "/user/user_userStation";
    }

    //站内信息查询更多
    @GetMapping("/userStationPage")
    public ModelAndView userStationPage(HttpServletRequest request,Model model){
        String userid = request.getParameter("userid");
        String page = request.getParameter("page");
        if(userid==null || page==null){
            return new ModelAndView();
        }

        List<AppUserMassageT> userMassage = userClientService.getUserMassage(Integer.valueOf(userid), Integer.valueOf(page));

        model.addAttribute("userMassage",userMassage);
        return new ModelAndView("/user/user_station_util");
    }

    //站内信息
    @GetMapping("/userMsgStatus")
    @ResponseBody
    public R userMsgStatus(HttpServletRequest request){
        String id = request.getParameter("id");
        R r = new R();
        if(id==null){
            r.setCode(301);
            r.setSuccess(false);
            r.setMessage("异常提交");
            return r;
        }
        //信息确认
        Boolean aBoolean = userClientService.userMsgStatus(Integer.valueOf(id));
        if(aBoolean){
            r.setCode(201);
            r.setSuccess(aBoolean);
            r.setMessage("已读");
            return r;
        }
        return R.error();
    }






    //修改用户信息
    @PostMapping("/updateUserInfo")
    @ResponseBody
    public R updateUserInfo(HttpServletRequest request,HttpServletResponse response){
        AppUserT getuser = userInfoUtils.getuser(request, response);
        String nick = request.getParameter("nick");
        String userDesc = request.getParameter("userDesc");
        System.out.println(nick);
        System.out.println(userDesc);

        getuser.setUserNickname(nick);
        getuser.setUserIntroduce(userDesc);
        System.out.println(getuser);
        return userClientService.userUpdate(getuser);
    }


    //上传头像
    @PostMapping("/userimgUpload")
    @ResponseBody
    public R userimgUpload(HttpServletRequest request,HttpServletResponse response) throws Exception {
        AppUserT getuser = userInfoUtils.getuser(request, response);
        R r = new R();
        if(getuser==null || getuser.getUserId()==null){
            r.setCode(301);
            r.setSuccess(false);
            r.setMessage("登录失效请重新登录");
            return r;
        }
        String upfile = request.getParameter("upfile");
        if(upfile==null){
           r.setCode(301);
           r.setSuccess(false);
           r.setMessage("图片格式不正确");
           return r;
        }

        String s = baseUpload.put64myImage(upfile);
        System.out.println("图片"+upfile);
        System.out.println(s);

        Boolean aBoolean = userClientService.userImgUpload(getuser.setImgPath(s));
        if(aBoolean){
            r.setCode(201);
            r.setSuccess(aBoolean);
            r.setMessage("修改成功");
            r.setData(s);
            return r;
        }
        return R.error();
    }


    @GetMapping("/user_newPass/{userid}")
    public String userNewPass(@PathVariable int userid){
        return "/user/user_newPassword";
    }

    @PostMapping("/userUpdatePwd")
    @ResponseBody
    public R userUpdatePwd(HttpServletRequest request,HttpServletResponse response){
        AppUserT getuser = userInfoUtils.getuser(request, response);
        R r = new R();
        if(getuser==null || getuser.getUserId()==null){
            r.setCode(301);
            r.setSuccess(false);
            r.setMessage("登录失效请重新登录");
            return r;
        }
        String pwdOld = request.getParameter("pwdOld"); //旧密码
        String pwd = request.getParameter("pwd");       //新密码
        System.out.println(pwdOld);
        System.out.println(pwd);
        if(pwdOld==null || pwd==null){
            r.setCode(301);
            r.setSuccess(false);
            r.setMessage("密码异常输入");
            return r;
        }
        if(!pwdOld.equals(getuser.getUserPassword())){
            r.setCode(301);
            r.setSuccess(false);
            r.setMessage("旧密码输入错误");
            return r;
        }

        Boolean aBoolean = userClientService.userUpdatePwd(getuser.setUserPassword(pwd));
        if(aBoolean){
            Cookie[] cookies = request.getCookies();
            //没有任何信息删除用户保存信息
            for(Cookie cookie: cookies){
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
            }


            r.setCode(201);
            r.setSuccess(aBoolean);
            r.setMessage("密码修改成功");
            return r;
        }
        return R.error();
    }



    @PostMapping("/userPhoneUpd")
    @ResponseBody
    public R userPhoneUpd(HttpServletRequest request){
        String userName = request.getParameter("userName");
        if(userName==null){
            return R.error();
        }
        System.out.println("修改手机号-------》");
        System.out.println(userName);
        R reg = userClientService.reg("2", userName, "4");
        return reg;
    }



    @PostMapping("/userPhoneUpdAdd")
    @ResponseBody
    public R userPhoneUpdAdd(HttpServletRequest request,HttpServletResponse response){
        AppUserT getuser = userInfoUtils.getuser(request, response);
        R r = new R();
        if(getuser==null || getuser.getUserId()==null){
              r.setCode(301);
              r.setSuccess(false);
              r.setMessage("登录失效请重新登录");
              return r;
        }

        String userName = request.getParameter("userName");
        String code = request.getParameter("code");
        System.out.println(userName);
        System.out.println(code);
        if(userName==null || code ==null){
            r.setCode(301);
            r.setSuccess(false);
            r.setMessage("修改信息错误");
            return r;
        }

        return userClientService.userPhoneUpd(userName,code,getuser.getUserId());
    }


    @GetMapping("/user_main/{userId}")
    public String userMain(@PathVariable int userId, HttpServletResponse response , HttpServletRequest request, Model model){
        System.out.println(userId);
        AppUserT uservo = userInfoUtils.getuser(request, response);
        if(uservo==null){
            return "login/login";
        }
        if(uservo.getUserId()==null){
            return "login/login";
        }
        model.addAttribute("uservo",uservo);
        return "user/user_main";
    }

    @GetMapping("/user_upd/{userId}")
    public String userUpd(){

        return "user/user_upd";
    }

    @GetMapping("/user_EmailUpd/{userId}")
    public String user_EmailUpd(){
        return "user/user_EmailUpd";
    }

    @PostMapping("/userEmail")
    @ResponseBody
    public R userEmail(HttpServletRequest request){
        String userName = request.getParameter("userName");
        if(userName==null){
            return R.error();
        }
        System.out.println("修改手机号-------》");
        System.out.println(userName);
        R reg = userClientService.reg("1", userName, "4");
        return reg;
    }


    @PostMapping("/userUpdEmail")
    @ResponseBody
    public R userEmail(HttpServletRequest request,HttpServletResponse response){
        AppUserT getuser = userInfoUtils.getuser(request, response);
        R r = new R();
        if(getuser==null || getuser.getUserId()==null){
            r.setCode(301);
            r.setSuccess(false);
            r.setMessage("登录失效请重新登录");
            return r;
        }

        String userName = request.getParameter("userName");
        String code = request.getParameter("code");
        if(userName==null || code ==null){
            r.setCode(301);
            r.setSuccess(false);
            r.setMessage("修改信息错误");
            return r;
        }
        System.out.println(userName);
        System.out.println(code);
        return userClientService.userEmailUpd(userName,code,getuser.getUserId());
    }


    @GetMapping("/user_solo")
    public String userSolo(){
        return "user/user_right_particulars";
    }

    @GetMapping("/user_messages")
    public String userMessages(){
        return "user/user_messages";
    }

    @GetMapping("/userProve")
    @ResponseBody
    public R userProve(HttpServletResponse response, HttpServletRequest request){
        AppUserT getuser = userInfoUtils.getuser(request, response);
        System.out.println("用户发布咨询 ------》");
        System.out.println(getuser);
        R r = new R();
        if(getuser!=null){
            r.setCode(201);
            r.setSuccess(true);
            r.setMessage("用户登录成功");
        }else{
            r.setCode(301);
            r.setSuccess(false);
            r.setMessage("未登录");
        }
        return r;
    }

    @PostMapping("/findpwd")
    @ResponseBody
    public R findpwd(HttpServletRequest request,HttpSession session){
        String type = request.getParameter("type");
        if(type==null){
            return R.error();
        }
        //    用户注册
        R r = new R();
        //1邮箱 2手机号
        if(!type.equals("1") && !type.equals("2")){
            r.setCode(301);
            r.setSuccess(false);
            r.setMessage("注册异常");
            return r;
        }
        String userName = request.getParameter("userName");
        String rcode = request.getParameter("rcode");
        Object kaptcha = session.getAttribute("kaptcha");   //获取保存的session验证码
        if(rcode==null){
            return R.error();
        }
        if(!rcode.equalsIgnoreCase(kaptcha+"")){
            r.setCode(301);
            r.setSuccess(false);
            r.setMessage("请输入正确图形验证码");
            return r;
        }
        //    邮箱修改密码 2手机号修改密码
        String userPassword = request.getParameter("userPassword");
        String code = request.getParameter("code");
        R findpwd = userClientService.findpwd(userName, userPassword, code, type);

        return findpwd;
    }



    //获取验证码
    @PostMapping("/user_reg")
    @ResponseBody
    public Object userReg(HttpServletRequest request,HttpSession session) throws MessagingException {
        String type = request.getParameter("type");
        if(type==null){
            return null;
        }
         //    用户注册
        R r = new R();
        if(!type.equals("1") && !type.equals("2")){
            r.setCode(301);
            r.setSuccess(false);
            r.setMessage("注册异常");
            return r;
        }
        String userName = request.getParameter("userName");
        String rcode = request.getParameter("rcode");
        Object kaptcha = session.getAttribute("kaptcha");   //获取保存的session验证码
        if(rcode==null){
            return null;
        }
        if(!rcode.equalsIgnoreCase(kaptcha+"")){
            r.setCode(301);
            r.setSuccess(false);
            r.setMessage("请输入正确图形验证码");
            return r;
        }
        //验证码类型
        String form = request.getParameter("form");
        if(!form.equals("1") && !form.equals("2") && !form.equals("3")){
            r.setCode(301);
            r.setSuccess(false);
            r.setMessage("注册异常");
            return r;
        }
        //1 邮箱注册 2手机号注册 3找回密码


        R reg = userClientService.reg(type, userName,form);

        return reg;
    }

    @PostMapping("/user_add")
    @ResponseBody
    public R userAdd(HttpServletRequest request){
        String userName = request.getParameter("userName");
        String code = request.getParameter("code");
        String userPassword = request.getParameter("pwd");
        String type = request.getParameter("type");
        R r = userClientService.userAdd(userName, code, userPassword,type);
        return r;
    }

    // 获取退出
    @GetMapping("/user_exit")
    public String userExit(HttpServletRequest request,HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        //没有任何信息删除用户保存信息
        for(Cookie cookie: cookies){
            cookie.setMaxAge(0);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        return "redirect:/";
    }


    /**
     * 验证码功能
     * @param response
     * @param session
     */
    @GetMapping("/user/kaptcha")
    public void getKaptcha(HttpServletResponse response, HttpSession session) {
        // 生成验证码
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);
        //log.info("验证码已生成");
        // 将验证码存入session
       System.out.println("session 的验证码"+session.getAttribute("kaptcha"));
        session.setAttribute("kaptcha", text);
        session.setMaxInactiveInterval(60);     //设置生存时间
        System.out.println(text);
        // 将突图片输出给浏览器
        response.setContentType("image/png");
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            //log.error("响应验证码失败:{}" ,e.getMessage());
            System.out.println(e.getMessage());
        }
    }




}
